package com.brush.brushbasicapi.mq.consumer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.brush.brushcommon.common.basic.pojo.BankOfTopic;
import com.brush.brushcommon.common.mq.pojo.MqError;
import com.brush.brushcommon.common.mq.service.MqErrorService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import static com.brush.brushcommon.common.mq.ExchangeConstants.*;

/**
 * @author cws
 * 监听消费者处理错误的消息
 */
@Component
@Slf4j
public class ErrorMassageListener {


    @Resource
    private MqErrorService mqErrorService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = QUEUE_DELETE_BASIC_ERROR),
                    exchange = @Exchange(name = EXCHANGE_DELETE_BASIC_ERROR, type = ExchangeTypes.DIRECT),
                    key = {ROUTING_KEY_DELETE_BASIC_ERROR}
            )
    )
    public void listenDirectQueue(Message message, long deliveryTag, Channel channel) {
        try {
            log.info("--------监听错误交换机到消息----------");
            Map<String, Object> headers = message.getMessageProperties().getHeaders();
            StringBuffer stringBuffer = new StringBuffer();
            //foreach遍历循环
            for (Map.Entry<String, Object> entry : headers.entrySet()) {
                stringBuffer.append(entry.getKey() + "---" + entry.getValue() + "\n");
            }
            MqError mqError = new MqError().setRequestParams(new String(message.getBody(), StandardCharsets.UTF_8))
                    .setErrorMsg(stringBuffer.toString());
            boolean save = mqErrorService.save(mqError);
            if (save) {
                log.info("--------已经成功添加到数据库----------");
            } else {
                log.error("--------添加到数据库失败----------");
            }
//         TODO 调用消息通知服务通知系统维修人员进行排查
        } catch (Exception e) {
            log.error("错误交换机出现异常：{}", e.getMessage());
        }
    }
}

